﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
using GPSMap.Core.Misc.DAL;
using HTMapLib;
using MapControl;
using MapControl.Misc;
using MapControl.Misc.DAL;
using MapControl.Misc.GPSPoint;

namespace GPSMap
{
    public partial class ucGPSDataGridView : UserControl
    {
        public ucVectShapeMap _objMapControl;
        private BindingSource bsGPSData;
        private AirPortRepository _airPortRespository;

        
        public ucGPSDataGridView()
        {
            InitializeComponent();
        }

        public void InitControl(ucVectShapeMap objMap, bool isUpdateDistance)
        {
            _objMapControl = objMap;

            dataGridViewGPS.RowPostPaint += new DataGridViewRowPostPaintEventHandler(DataGridView_RowPostPaint);

            _airPortRespository = new AirPortRepository(GeneralClass.appDBFile);
            LoadAirport();


            InitCombobox_Planes();

            LoadDataGridView(0, 0);
            FormatDataGridView();
        }

        public void Reset()
        {
            toolStripLabelConnectDBFile.Text = "";
            lblDate.Text = "";
            InitCombobox_Planes();
        }

        public void LoadAirport()
        {
            comboBoxAirport.ValueMember = "airport_id";
            comboBoxAirport.DisplayMember = "airport_name";
            comboBoxAirport.DataSource = _airPortRespository.GetAll().DefaultView;
            comboBoxAirport.SelectedValue = 1; //Mặc định sân bay TSN
        }

        public DataGridView DataGridViewGPS
        {
            get { return dataGridViewGPS; }
        }


       

        /// <summary>
        /// Cập nhật Datasource từ CSDL
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        public void LoadDataGridView(int min, int max)
        {
            toolStripLabelConnectDBFile.Text = "File dữ liệu: " + Path.GetFileName(GeneralClass.gpsDBFile);
            GeneralClass.InitLoadDatabase(min, max);
            
            bsGPSData = new BindingSource();
            bsGPSData.DataSource = GeneralClass.dbTestGPS.DefaultView;
            dataGridViewGPS.DataSource = bsGPSData;
            bindingNavigator1.BindingSource = bsGPSData;
            FormatDataGridView();
            if (GeneralClass.dbTestGPS.Rows.Count > 0)
            {
                DateTime dt = Convert.ToDateTime(GeneralClass.dbTestGPS.Rows[0]["time"]);
                lblDate.Text = dt.ToString("dd/MM/yyyy");
            }
            else
            {
                lblDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            }

            
            UpdateDistance();
            UpdatePlaneNames();
        }

        /// <summary>
        /// Cập nhật datasource theo datatable đã có
        /// </summary>
        /// <param name="gpsDB"></param>
        public void UpdateDataGridView(DataTable gpsDB)
        {
            bsGPSData = new BindingSource();
            bsGPSData.DataSource = gpsDB.DefaultView;
            dataGridViewGPS.DataSource = bsGPSData;
            bindingNavigator1.BindingSource = bsGPSData;
        }

        ///// <summary>
        ///// Cập nhật danh sách Planes đang có
        ///// </summary>
        //public void LoadCombobox_Planes()
        //{
        //    //Load danh sách Plane
        //    PlaneRepository objPlaneRepository = new PlaneRepository(GeneralClass.appDBFile);
        //    comboBoxPlane.DataSource = objPlaneRepository.GetAll();
        //    comboBoxPlane.DisplayMember = "name";
        //    comboBoxPlane.ValueMember = "code";
        //}


        /// <summary>
        /// Cập nhật danh sách Planes đang có
        /// </summary>
        public void UpdateCombobox_Planes(string code)
        {
            PlaneRepository objPlaneRepository = new PlaneRepository();
            Plane objPlane = null;
            if (!objPlaneRepository.IsExist_Code(code))
            {
                //Thêm mới dữ liệu máy bay
                objPlane = new Plane();
                objPlane.Code = code;
                objPlane.Name = code;
                objPlaneRepository.Insert(objPlane);
                GeneralClass.planeDict.Add(code, code);
            }

            //Load danh sách Plane
            objPlane = objPlaneRepository.GetPlane(code);

            comboBoxPlane.Items.Add(objPlane);
        }
        
        public void InitCombobox_Planes()
        {
            //_planeDict = new Dictionary<string, string>();
            comboBoxPlane.Items.Clear();
            comboBoxPlane.Items.Add(new Plane(-1, "", ""));
        }

        /// <summary>
        /// Load danh sách name có trong table gspdata
        /// </summary>
        public void LoadCombobox_Planes()
        {
            //Cập nhật lại combobox plane
            InitCombobox_Planes();
            //Load danh sách Planes
            DataTable dbPlaneName = GPSDataRepository.GetPlaneNames();
            foreach (DataRow dr in dbPlaneName.Rows)
            {
                string name = dr["name"].ToString().Trim();
                //Cập nhật plane vào combobox
                UpdateCombobox_Planes(name);
            }
            comboBoxPlane.SelectedIndex = 0;
        }

        public void FormatDataGridView()
        {
            dataGridViewGPS.Columns["id"].Visible = false;
            dataGridViewGPS.Columns["airport_id"].Visible = false;
            dataGridViewGPS.Columns["name"].Visible = false;

            dataGridViewGPS.Columns["id"].HeaderText = "Stt";
            dataGridViewGPS.Columns["showname"].HeaderText = "Tên";
            dataGridViewGPS.Columns["showname"].DisplayIndex = 1;
            dataGridViewGPS.Columns["lat"].HeaderText = "Vĩ độ";
            dataGridViewGPS.Columns["lon"].HeaderText = "Kinh độ";
            dataGridViewGPS.Columns["alt"].HeaderText = "Độ cao";
            dataGridViewGPS.Columns["alt"].ToolTipText = "Độ cao (m)";
            dataGridViewGPS.Columns["speed"].HeaderText = "Tốc độ";
            dataGridViewGPS.Columns["speed"].ToolTipText = "Tốc độ (km/h)";
            dataGridViewGPS.Columns["angle"].HeaderText = "Hướng";
            dataGridViewGPS.Columns["angle"].ToolTipText = "Hướng so với bắc bán cầu";
            dataGridViewGPS.Columns["distance"].HeaderText = "Cự ly";
            dataGridViewGPS.Columns["distance"].ToolTipText = "Khoảng cách tính từ sân bay (km)";
            dataGridViewGPS.Columns["time"].HeaderText = "Th.gian";
            dataGridViewGPS.Columns["time"].ToolTipText = "Thời gian";
            dataGridViewGPS.Columns["satnum"].HeaderText = "Vệ tinh";
            dataGridViewGPS.Columns["satnum"].ToolTipText = "Số vệ tinh đang dùng";

            dataGridViewGPS.Columns["id"].Width = 35;
            dataGridViewGPS.Columns["showname"].Width = 35;
            dataGridViewGPS.Columns["showname"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewGPS.Columns["lat"].Width = 55;
            dataGridViewGPS.Columns["lat"].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPS.Columns["lon"].Width = 60;
            dataGridViewGPS.Columns["lon"].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPS.Columns["alt"].Width = 48;
            dataGridViewGPS.Columns["alt"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPS.Columns["speed"].Width = 49;
            dataGridViewGPS.Columns["speed"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPS.Columns["angle"].Width = 41;
            dataGridViewGPS.Columns["angle"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPS.Columns["distance"].Width = 41;
            dataGridViewGPS.Columns["distance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPS.Columns["time"].Width = 50;
            dataGridViewGPS.Columns["time"].DefaultCellStyle.Format = "HH:mm:ss";
            dataGridViewGPS.Columns["satnum"].Width = 50;
            dataGridViewGPS.Columns["satnum"].DefaultCellStyle.Format = "0#";
            dataGridViewGPS.Columns["satnum"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            
        }

        //public MouseEventHandler DataGridViewGPSData_MouseDoubleClickEvent;
        private void dataGridViewGPSData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (DataGridViewGPSData_MouseDoubleClickEvent != null)
            //    DataGridViewGPSData_MouseDoubleClickEvent(sender, e);

            try
            {
                if (dataGridViewGPS.CurrentRow != null)
                {
                    BaseGPSPoint objPoint = new GPSNormalPoint(GeneralClass.dbTestGPS.Rows[dataGridViewGPS.CurrentCell.RowIndex]);
                    _objMapControl.ucMap1.Map.ZoomTo(_objMapControl.ucMap1.Map.Zoom, objPoint.objGPSData.LonGPS,
                                                     objPoint.objGPSData.LatGPS);
                    _objMapControl.Refresh();

                    Graphics g = _objMapControl.ucMap1.Map.CreateGraphics();
                    //Tính lại tọa độ tâm center để vẽ object
                    float centerX, centerY;
                    centerX = centerY = 0;
                    _objMapControl.ucMap1.Map.ConvertCoord(ref centerX, ref centerY, ref objPoint.objGPSData.LonGPS,
                                                           ref objPoint.objGPSData.LatGPS,
                                                           MapXLib.ConversionConstants.miMapToScreen);
                    objPoint.CenterPoint = new PointF(centerX, centerY);
                    objPoint.Draw(g, Color.Red);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            }
        }


        //public EventHandler DataGridViewGPSData_CurrentCellChangedEvent;
        private void dataGridViewGPSData_CurrentCellChanged(object sender, EventArgs e)
        {
            //if (DataGridViewGPSData_CurrentCellChangedEvent != null)
            //    DataGridViewGPSData_CurrentCellChangedEvent(sender, e);
            
            //try
            //{
            //    if (dataGridViewGPS.CurrentRow != null)
            //    {
            //        //int airport_id =
            //        //    int.Parse(
            //        //        GeneralClass.dbTestGPS.Rows[dataGridViewGPS.CurrentCell.RowIndex][
            //        //            "airport_id"].ToString());
            //        //Airport objAirport = _airPortRespository.GetAirportById(airport_id);

            //        //BaseGPSPoint objPoint =
            //        //    new GPSNormalPoint(
            //        //        GeneralClass.dbTestGPS.Rows[dataGridViewGPS.CurrentCell.RowIndex]);
            //        //toolStripStatusLabelDistance.Text = string.Format("Cách sân bay \"{0}\" khoảng {1} km",
            //        //                                                  objAirport.Airport_Name,
            //        //                                                  objPoint.objGPSData.Distance.ToString("#,##0"));
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            //}
        }

        public EventHandler ucGPSDataGridView_ResizeEvent;
        private void ucGPSDataGridView_Resize(object sender, EventArgs e)
        {
            if (ucGPSDataGridView_ResizeEvent != null)
                ucGPSDataGridView_ResizeEvent(sender, e);
        }

        
        private void comboBoxAirport_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GeneralClass.objCurrAirport = _airPortRespository.GetAirportById(int.Parse(comboBoxAirport.SelectedValue.ToString())); //_airPortRespository.GetCurrentAirport();
                UpdateDistance();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            }
            
        }

        /// <summary>
        /// Cập nhật khoảng cách của sân bay so với các tọa độ gps
        /// </summary>
        public void UpdateDistance()
        {
            foreach (DataGridViewRow r in DataGridViewGPS.Rows)
            {
                //BaseGPSPoint objPoint = new GPSNormalPoint(GeneralClass.dbTestGPS.Rows[r.Index]);
                //int distance = (int)_objMapControl.ucMap1.Map.Distance(GeneralClass.objCurrAirport.Longitude, GeneralClass.objCurrAirport.Latitude,
                //                                          double.Parse(GeneralClass.dbTestGPS.Rows[r.Index]["lon"].ToString()), double.Parse(GeneralClass.dbTestGPS.Rows[r.Index]["lat"].ToString()))/1000;
                //GPSDataRepository.UpdateDistance((int)GeneralClass.dbTestGPS.Rows[r.Index]["id"], distance);
                //Chuyển đổi cự ly theo kilomet
                //objPoint.objGPSData.Distance = distance;//(int)distance / 1000;
                //objPoint.objGPSData.Airport_Id = GeneralClass.objCurrAirport.Airport_Id;
                //GPSDataRepository.Save(objPoint.objGPSData);
                //r.Cells["distance"].Value = objPoint.objGPSData.Distance;
                //r.Cells["distance"].Value = distance;
                //r.Cells["airport_id"].Value = GeneralClass.objCurrAirport.Airport_Id;

                r.Cells["distance"].Value = (int)_objMapControl.ucMap1.Map.Distance(GeneralClass.objCurrAirport.Longitude, GeneralClass.objCurrAirport.Latitude,
                                                          double.Parse(GeneralClass.dbTestGPS.Rows[r.Index]["lon"].ToString()), double.Parse(GeneralClass.dbTestGPS.Rows[r.Index]["lat"].ToString())) / 1000;
            }
            dataGridViewGPSData_CurrentCellChanged(null, null);
        }

        /// <summary>
        /// Thay đổi tên máy bay gps trả về thành tên máy bay trong csdl appdata.sdf
        /// </summary>
        public void UpdatePlaneNames()
        {
            foreach (DataGridViewRow r in DataGridViewGPS.Rows)
            {
                string name = r.Cells["name"].Value.ToString().Trim();
                //Cập nhật plane vào combobox
                if (!GeneralClass.planeDict.ContainsKey(name))
                    UpdateCombobox_Planes(name);
                r.Cells["showname"].Value = GeneralClass.planeDict[name];
            }
        }

        private void checkBoxViewLastestPoint_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                GeneralClass.IsViewLatestGPSPoint = checkBoxViewLastestPoint.Checked;
                _objMapControl.ucMap1.Map.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            }
           
        }

        private void btnAirportPos_Click(object sender, EventArgs e)
        {
            try
            {
                Airport objAirport = _airPortRespository.GetAirportById(int.Parse(comboBoxAirport.SelectedValue.ToString()));
                GeneralClass.IsViewAirport = true;
                _objMapControl.ucMap1.Map.ZoomTo(_objMapControl.ucMap1.Map.Zoom, objAirport.Longitude, objAirport.Latitude);
                _objMapControl.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            }
        }

        private void comboBoxPlane_SelectedIndexChanged(object sender, EventArgs e)
        {
            Plane obj = (Plane) comboBoxPlane.SelectedItem;
            if (obj.Id != -1)
                GeneralClass.objCurrPlane = obj;
            else
                GeneralClass.objCurrPlane = null;
            LoadDataGridView(GeneralClass.min, GeneralClass.max);
        }

        public void UpdateStatus(bool isEnable)
        {
            comboBoxPlane.Enabled = isEnable;
        }

        /// <summary>
        /// Thêm stt ở row header
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, grid.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
        }

        private void xóaĐiểmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn thật sự muốn xóa điểm này?", "Cảnh báo", MessageBoxButtons.YesNo) ==
                DialogResult.Yes)
            {
                GPSDataRepository.Delete((int) GeneralClass.dbTestGPS.Rows[currentMouseOverRow]["id"]);
                GeneralClass.dbTestGPS.Rows.RemoveAt(currentMouseOverRow);
                //dataGridViewGPS.Rows.RemoveAt(currentMouseOverRow);
                _objMapControl.Refresh();
            }
        }

        private int currentMouseOverRow = -1;
        private void dataGridViewGPS_MouseClick(object sender, MouseEventArgs e)
        {
            currentMouseOverRow = dataGridViewGPS.HitTest(e.X, e.Y).RowIndex;

            
            if (e.Button == MouseButtons.Right)
            {
                if (currentMouseOverRow >= 0)
                {
                    dataGridViewGPS.Rows[currentMouseOverRow].Selected = true;
                    dataGridViewGPS.ContextMenuStrip = contextMenuStrip1;
                    contextMenuStrip1.Show(dataGridViewGPS, new Point(e.X, e.Y));
                }
            }
            dataGridViewGPS.ContextMenuStrip = null;
        }

        private void btnBackupFile_Click(object sender, EventArgs e)
        {
            try
            {
                //string backupFile = GeneralClass.BackupDB(GeneralClass.gpsDBFile);
                string backupFile = GeneralClass.BackupDB(GeneralClass.gpsDBFile);
                
                if (backupFile != "")
                    MessageBox.Show("Lưu thành công ở " + backupFile);
                else
                    MessageBox.Show("Không có dữ liệu để sao lưu");
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
            }
        }

    }
}
